package top.cyuw.simplerpc.factory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chen
 * @date 2023/3/13 23:03
 */
public class SingletonFactory {

    private static final Map<String, Object> INSTANCE_MAP = new ConcurrentHashMap<>();

    private SingletonFactory() {

    }

    public static <T> T getInstance(Class<T> clazz) {
        Object instance = INSTANCE_MAP.computeIfAbsent(clazz.toString(), k -> {
            try {
                return clazz.getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        });
        return clazz.cast(instance);
    }

}
